package com.fan.websocketstudy.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Author: fan
 * @CreateTime 2024/6/1 23:34
 * @Description
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
@Tag(name = "文件", description = "文件工具类")
public class FileController {


    @Operation(summary = "上传文件", description = "上传文件")
    @PostMapping("/uploadFile")
    public ResponseEntity<String> uploadFile(MultipartFile file) {

            String rootPath =  File.separator + "data";

            // 文件存放服务端的位置
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists())
                dir.mkdirs();
            // 写文件到服务器
            File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
            // 以流的形式保存文件
            try (InputStream inputStream = file.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(serverFile)) {

                byte[] buffer = new byte[4096];
                int bytesRead = -1;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                // 输出流会自动关闭，因为我们使用了try-with-resources
                // 但为了确保文件已正确写入，我们可以显式地调用flush()
                outputStream.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }

        return new ResponseEntity<>(rootPath + File.separator + "tmpFiles"+ File.separator + file.getOriginalFilename(), HttpStatus.OK);
    }



    @Operation(summary = "下载文件", description = "下载文件")
    @GetMapping("/downloadFile")
    public void downloadFile(String filePath,HttpServletResponse response) {

        // 文件的绝对路径

        // 获取文件名（如果需要，可以用于设置Content-Disposition头部）
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        // 设置响应头部
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        // 读取文件并写入响应输出流
        try (InputStream in = new FileInputStream(filePath);
             OutputStream out = response.getOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            out.flush(); // 确保所有数据都发送给了客户端

        } catch (IOException e) {
            e.printStackTrace();
            // 可以在这里设置错误响应，比如404或500
        }

    }



}
